//
//  MainViewController.swift
//  Weibo10
//
//  Created by lirenqiang on 16/7/21.
//  Copyright © 2016年 lirenqiang. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    //MARK: - 监听方法
    /// 如果单纯使用 `private` 运行循环将无法正确发送消息
    /// 如果使用@objc 修饰符, 可以保证运行循环能够发送此消息
    @objc private func clickComposeButton() {
        print("点我了")
    }
    
    //MARK: - 视图声明周期函数
    override func viewDidLoad() {
        super.viewDidLoad()

        //添加控制器,并不会创建tabBar控制器中的按钮
        // 懒加载是无处不在的,所有控件都是延迟创建的.
        addChildViewControllers()
        
//        print(tabBar.subviews)
        
        setupComposedButton()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        //将撰写按钮弄到最前面
        tabBar.bringSubviewToFront(composeButton)
//        print(tabBar.subviews)
    }
    
    // MARK: -懒加载控件
    private lazy var composeButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add", 
        backImageName: "tabbar_compose_button")
}


//MARK: -设置界面
extension MainViewController {
    
    /// 设置撰写按钮
    private func setupComposedButton() {
        tabBar.addSubview(composeButton)
//        composeButton.center = tabBar.center
        // 调整按钮
        let count = childViewControllers.count 
        //让按钮宽一点点,能够解决手指触摸的容错处理.
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composeButton.frame = CGRectInset(tabBar.bounds, 2*w, 0)
        
        composeButton.addTarget(self, action: #selector(clickComposeButton), forControlEvents: .TouchUpInside )
        
    }
    
    /// 添加所有的控制器
    private func addChildViewControllers() {
        
        //设置tintColor -图片渲染颜色
        //如果能够用颜色解决,就不建议使用图片.
        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    /// 添加控制
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
                
        //设置标题
        vc.title = title
        
        //设置图像
        vc.tabBarItem.image = UIImage(named: imageName)
        
        //导航控制器
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }
    
}